// assets/scripts/utils/SignManager.ts
import sha256 from 'js-sha256';

/**
 * 签名管理器
 * 用于生成API请求签名
 */
export class SignManager {
  // 签名密钥
  private static readonly SECRET_KEY: string = "pancake_2023_v1";

  /**
   * 生成签名
   * @param deviceId 设备ID
   * @returns 签名字符串
   */
  public static generateSignature(deviceId: string): string {
    if (!deviceId) {
      console.error('设备ID为空，无法生成签名');
      return '';
    }

    try {
      // 签名规则: sha256(deviceId + SECRET_KEY)
      const signString = deviceId + this.SECRET_KEY;
      return sha256(signString);
    } catch (error) {
      console.error('生成签名失败:', error);
      return '';
    }
  }

  /**
   * 将对象按键名排序后序列化为字符串
   */
  private static stringifyObject(obj: Record<string, any>): string {
    const sortedKeys = Object.keys(obj).sort();
    return sortedKeys.map(k => `${k}=${obj[k]}`).join('&');
  }

  /**
   * 验证签名是否一致
   */
  public static verifySignature(data: Record<string, any> | string, signature: string): boolean {
    return this.generateSignature(data as string) === signature;
  }
}
